package com.unicom.projt;

import android.util.Log;
import com.unicom.projt.db.Account;
import com.unicom.projt.db.DB;
import com.unicom.projt.db.DBConfig;
import com.unicom.projt.http.AbstractHttpController;
import com.unicom.projt.http.UriConstants;
import com.unicom.projt.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Lee
 * Date: 11-12-12
 * Time: 下午5:53
 */
public class MainController extends AbstractHttpController<String> {
    private Main mActivity;
    private DB mDB;
    private String phoneNumber;
    private String password;
    private String userName="  ";

    /**
     * 初始化网络连接工具类和GUI Handler。
     */
    public MainController(Main main) {
        super(String.class);
        this.mActivity = main;
        mDB = DB.getInstance(mActivity);
    }

    @Override
    public void onNetworkAbort() {
        ToastUtils.showMessage(mActivity, "错误，网络连接被中断.");
        mActivity.hideProgressDialog();
    }

    @Override
    public void onNetworkError() {
        ToastUtils.showMessage(mActivity, "网络连接错误");
        mActivity.hideProgressDialog();
    }

    @Override
    public void onRequestFinish(String response) {
        mActivity.hideProgressDialog();
       if(response==null || "".equals(response) ){
           ToastUtils.showMessage(mActivity,"错误，请稍候再试");
           return;
       }
        String resCode=SimpleXmlParser.getResponseCode(response);
        //AlertDialogUtils.showConfirmDiaLog(mActivity,SimpleXmlParser.getResponseDes(response));
        if (ResponseCode.SUCCESS.equals(resCode)) {
            UserHolder.phoneNumber = phoneNumber;
            UserHolder.password = password;
            UserHolder.userName = userName;

            DB db=DB.getInstance(mActivity);
            db.open();
            db.clearDBTableByName(DBConfig.Account.TABLE_NAME);
            Account account=new Account();
            account.phoneNumber=phoneNumber;
            db.insertAccount(account);
            db.close();

            PageJumpUtils.jump(mActivity, Home.class);
            mActivity.finish();
        }else if(ResponseCode.errorCodeMap.containsKey(resCode.trim())){
            ToastUtils.showMessage(mActivity,ResponseCode.errorCodeMap.get(resCode.trim()));
        }
        else{
            ToastUtils.showMessage(mActivity, "错误，系统未知错误");
        }
    }

    @Override
    public void onResponseError() {
        ToastUtils.showMessage(mActivity, "错误，返回结果错误");
        mActivity.hideProgressDialog();
    }


    public void login(String phoneNumber, String password) {
        this.phoneNumber = phoneNumber;
        this.password = password;
        String xml = new PostXmlBuilder().setBiPCode(RequestCode.LOGIN_AUTH).setTelNo(phoneNumber).setUserPas(password).createXml();
        this.sendRequest(UriConstants.URL, xml);
    }


}
